import 'dart:math';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:moment_dart/moment_dart.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:spendbook/common/constants.dart';
import 'package:spendbook/common/widgets.dart';
import 'package:spendbook/models/record.dart';

class RecordScreen extends StatefulWidget {
  RecordScreen({Key? key}) : super(key: key);

  @override
  _RecordScreenState createState() => _RecordScreenState();
}

class _RecordScreenState extends State<RecordScreen> {
  List<Record> _records = [];
  String? _filter;
  DateTimeRange? _between;
  RefreshController _refreshController = RefreshController();
  int _loaded = 0;

  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback((_) {
      _refreshController.requestRefresh();
    });
  }

  Future<void> _getList() async {
    Map<String, String> _para = {};
    if (_filter != null) {
      _para['filter'] = _filter!;
    }
    if (_between != null) {
      _para['start'] = _between!.start.toString();
      _para['end'] = _between!.end.toString();
    }
    List _list = await Record().fetch(_para);
    if (mounted) {
      setState(() {
        _records.clear();
        _list.forEach((_item) => _records.add(Record()..fromJson(_item)));
        _loaded = 1;
      });
    }
    _refreshController.refreshCompleted();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('消费记录'), actions: <Widget>[
        IconButton(
          icon: Icon(Icons.date_range),
          onPressed: () async {
            final DateTimeRange? picked = await showDateRangePicker(context: context, locale: Locale('zh'), firstDate: Moment.now().subtract(Duration(days: 365)).date, lastDate: DateTime(2025));
            if (_between != picked) {
              _between = picked;
              _refreshController.requestRefresh();
            }
          },
        ),
        PopupMenuButton(
          icon: Icon(Icons.more_vert),
          itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
            const PopupMenuItem<String>(
              value: 'all',
              child: Text('查看全部'),
            ),
            const PopupMenuItem<String>(
              value: 'self',
              child: Text('只看自己'),
            ),
          ],
          onSelected: (String selected) async {
            _filter = selected;
            _refreshController.requestRefresh();
          },
        ),
      ]),
      body: SmartRefresher(
        controller: _refreshController,
        onRefresh: _getList,
        child: ListView.separated(
            separatorBuilder: listSeparatorBuilder,
            itemCount: _records.length > 0 ? _records.length : _loaded,
            padding: EdgeInsets.only(bottom: 60),
            itemBuilder: (BuildContext context, int index) {
              if (_records.isEmpty) return NoData();
              Record _record = _records[index];
              return Slidable(
                key: ValueKey(index),
                child: ListTile(
                  leading: CircleAvatar(
                    child: Text(_record.metadata!['creator'].toString().substring(0, min(_record.metadata!['creator'].length, 2))),
                  ),
                  title: Text('[${_record.category}]${_record.description}'),
                  subtitle: Text(_record.createdAt!.format((_record.createdAt!.isBefore(Moment.now()) ? 'y年' : '') + 'MM月DD日 HH:mm')),
                  trailing: Text(toStringAsMoney(_record.fee, fractionDigits: null)),
                ),
                enabled: _record.metadata!['isSelf'],
                endActionPane: ActionPane(
                  motion: const DrawerMotion(),
                  extentRatio: 0.25,
                  children: <Widget>[
                    SlidableAction(
                      label: '删除',
                      foregroundColor: Colors.white,
                      backgroundColor: Colors.red,
                      onPressed: (context) async {
                        final res = await showOkCancelAlertDialog(
                          context: context,
                          title: '确定删除?',
                          message: '确定要删除该记录?',
                        );
                        if (res == OkCancelResult.ok) {
                          await _record.delete();
                          setState(() {
                            _records.removeAt(index);
                          });
                        }
                      },
                    ),
                  ],
                ),
              );
            }),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () async {
          final _record = await Navigator.pushNamed(context, '/record/add') as Record?;
          if (_record != null) {
            setState(() {
              _records.insert(0, _record);
            });
          }
        },
      ),
    );
  }
}
